const handler = require('sv-handler')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 职业列表
  async professionList() {
    let {
      profession_id,
      profession_name,
    } = this.params

    const dbJQL = uniCloud.databaseForJQL({
      clientInfo: this.getClientInfo()
    })

    const tempLibsDB = dbJQL.collection('sv-exam-libs')
      .field('lib_id,lib_name,lib_title,icon,sell_num,fav_num,vip').getTemp()

    // 连接表实例
    let query = dbJQL.collection('sv-exam-professions', tempLibsDB)

    // 构建筛选条件(对象形式)
    const conditions = {}
    if (profession_id) {
      conditions.profession_id = dbCmd.eq(profession_id)
    }
    if (profession_name) {
      conditions.profession_name = dbCmd.eq(profession_name)
    }
    // 将所有有效的筛选条件添加到查询对象中
    if (Object.keys(conditions).length > 0) {
      query = query.where(conditions)
    }

    const professionRes = await query.orderBy('sort', 'asc').get()

    return handler.result({
      data: professionRes.data,
    })
  },
  // 更新职业
  async professionUpdate() {
    const {
      _id,
      profession_id,
      profession_name
    } = this.params

    if (!profession_id || !profession_name) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const professionRes = await db.collection('sv-exam-professions').doc(_id).update(this.params)

    return handler.result({
      data: professionRes,
    })
  },
  // 添加职业
  async professionAdd() {
    const {
      profession_id,
      profession_name
    } = this.params

    if (!profession_id || !profession_name) {
      throw handler.result({
        code: 40001
      })
    }

    const professionRes = await db.collection('sv-exam-professions').add(this.params)

    return handler.result({
      data: professionRes,
    })
  },
  // 删除职业
  async professionDelete() {
    const {
      profession_id
    } = this.params

    if (!profession_id) {
      throw handler.result({
        code: 40001
      })
    }

    const professionRes = await db.collection('sv-exam-professions').where({
      "profession_id": Array.isArray(profession_id) ? dbCmd.in(profession_id) : dbCmd.eq(profession_id)
    }).remove()

    return handler.result({
      data: professionRes,
    })
  },
}